﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using ROOT.CIMV2.Win32;

namespace ProcessInterceptor
{
	public delegate void ProcessEventHandler(Win32_Process proc);

	public class ProcessWatcher : ManagementEventWatcher
	{
		public event ProcessEventHandler ProcessCreated;

		// WMI WQL запросы
		static readonly string WMI_OPER_EVENT_QUERY = @"SELECT * FROM __InstanceOperationEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_Process'"; // запрос на получения списка всех процессов
		static readonly string WMI_OPER_EVENT_QUERY_WITH_PROC = WMI_OPER_EVENT_QUERY + "and TargetInstance.Name = '{0}'"; // запрос на получение конкретного процесса по имени запущеного .exe файла

		public ProcessWatcher(string process)
		{
			
			this.Query.QueryLanguage = "WQL";
			if (string.IsNullOrEmpty(process))
			{
				this.Query.QueryString = WMI_OPER_EVENT_QUERY;
			}
			else
			{
				this.Query.QueryString =
				string.Format(WMI_OPER_EVENT_QUERY_WITH_PROC, process);
			}
			
			this.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
			this.Options = new EventWatcherOptions(null, TimeSpan.FromMilliseconds(500), 1);
		}

		private void watcher_EventArrived(object sender, EventArrivedEventArgs e)
		{
			string eventType = e.NewEvent.ClassPath.ClassName;
			Win32_Process proc = new
			Win32_Process(e.NewEvent["TargetInstance"] as ManagementBaseObject);

			if (eventType == "__InstanceCreationEvent")
				if (ProcessCreated != null)
					ProcessCreated(proc);
		}		
   	}
}
